require('@babel/register')
require('@babel/polyfill')

const Koa = require('koa')
const path = require('path')
const koaNunjucks = require('koa-nunjucks-2');
const bodyparser = require('koa-bodyparser')
const router = require('./middleware/router')
const db = require('./database/init')
const session  = require('koa-session')
const static = require('koa-static')
const Redis = require('ioredis');

const app = new Koa()

//配置静态资源目录
app.use(static(path.resolve(__dirname,'./public')))

//配置redis
const redis = new Redis(6379, '127.0.0.1');

const store = {
  async get (key, maxAge) {
    console.log(key)
    return JSON.parse(await redis.get(key))
  },
  async set (key, sess, maxAge) {
    const result = await redis.set(key, JSON.stringify(sess))
  },
  destroy (key) {
    redis.del(key)
  }
}

//配置session
app.keys = ['admimPD123'] //加密cookie用
const CONFIG = {
  key: 'koa:sess', /** (string) cookie key (default is koa:sess) */
  /** (number || 'session') maxAge in ms (default is 1 days) */
  /** 'session' will result in a cookie that expires when session/browser is closed */
  /** Warning: If a session cookie is stolen, this cookie will never expire */
  maxAge: 86400000,
  overwrite: true, /** (boolean) can overwrite or not (default true) */
  httpOnly: true, /** (boolean) httpOnly or not (default true) */
  signed: true, /** (boolean) signed or not (default true) */
  rolling: false, /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */
  renew: false, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/
  store
};
app.use(session(CONFIG, app));

//配置bodyparser解析post请求
app.use(bodyparser())

//配置模板引擎nunjucks
app.use(koaNunjucks({
    ext: 'html',
    path: path.resolve(__dirname, './views'),
    nunjucksConfig: {
      trimBlocks: true
    }
  }));
  
//连接数据库,初始化模型
db.connectdb()
db.initSchema()

//执行路由配置
router(app) 


app.listen(3000)